package com.cloudbroker.bcs.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudbroker.bcs.common.context.RuntimeContext;

public class EnvironmentUtils {
    private static Logger logger = LoggerFactory.getLogger(EnvironmentUtils.class);
    
    private static final String RUNTIME_CONFIG_ROOT_ENV_KEY = "RUNTIME_CONFIG_ROOT";
    
    private static final String RUNTIME_CONFIG_ROOT_DIR_NAME = "runtime_config_root";
    
    private static final String CLASSPATH_PREFIX = "classpath:";
    
    public static boolean isOnWindows() {
        String os = System.getProperty("os.name").toLowerCase();
        return os.indexOf("win") >= 0;
    }
    
    /**
     * 获取系统运行期配置文件路径
     * @return
     */
    public static String getRuntimeConfigPath() {
        String path = System.getenv().get(RUNTIME_CONFIG_ROOT_ENV_KEY);
        if (StringUtils.isBlank(path)) {
            if (isOnWindows()) {
                path = "C:" + File.separator + RUNTIME_CONFIG_ROOT_DIR_NAME;
            } else {
                path = '/' + RUNTIME_CONFIG_ROOT_DIR_NAME;
            }
        }
        return path;
    }
    
    public static String findFileInRuntimeConfigDirOrClasspath(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        boolean inClasspath = false;
        if (fileName.startsWith(CLASSPATH_PREFIX)) {
            inClasspath = true;
            fileName = fileName.substring(CLASSPATH_PREFIX.length());
        }
        if (fileName.startsWith("/")) {
            fileName = fileName.substring(1);
        }
        if (!inClasspath) {
            String filePath = getRuntimeConfigPath() + File.separator + fileName;
            File file = new File(filePath);
            if (file.exists()) {
                return filePath;
            }
        }
        String filePath = getClasspathRoot() + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            return filePath;
        }
        return null;
    }
    
    /**
     * 获取Classpath根目录地址
     * @return
     */
    public static String getClasspathRoot() {
        return Thread.currentThread().getContextClassLoader().getResource("").getPath();
    }
    
    /**
     * 获取Web部署实际根目录
     * @return
     */
    public static String getWebRootPath() {
        return RuntimeContext.getServletContext().getRealPath("/");
    }

    public static void execInThread(final String command) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                exec(command);
            }
        }).start();
    }

    public static void exec(String command) {
        try {
            logger.error(command);
            Process proc = Runtime.getRuntime().exec(command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            System.out.println("<error></error>");
            while ((line = br.readLine()) != null)
                System.out.println(line);
            System.out.println("");
            int exitVal = proc.waitFor();
            logger.error("Process exitValue: " + exitVal);
        }catch (Exception e) {
            logger.error("exec command : " + command +"error " , e);
            throw new RuntimeException(e);
        }
    }
}
